package com.maszy.commons.tools;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.MediaSizeName;
import javax.swing.JOptionPane;

import com.maszy.bean.Dept;
import com.maszy.bean.DoorStore;
import com.maszy.bean.GoodPlan;
import com.maszy.bean.Product;
import com.maszy.db.ConfigurableConstants;
import com.maszy.service.DeptService;
import com.maszy.service.DoorStoreService;
import com.maszy.service.GoodPlanService;

public class PrintGoodPlanReport2 implements Printable {
	private int PAGES = 0;
	/*
	 * Graphic指明打印的图形环境；PageFormat指明打印页格式（页面大小以点为计量单位，
	 * 1点为1英寸的1/72，1英寸为25.4毫米。A4纸大致为595×842点）；page指明页号
	 */
	private final int _titleFontSize = 14;
	private final int _contentFontSize = 12;
	private final int _x = 20;
	private final int _x2 = 300;
	private final int _y = 20;
	private final int step = 20;
	String goodType = "";
	private GoodPlan goodPlan;
	private DoorStore doorStore;
	private String type;

	public int print(Graphics gp, PageFormat pf, int page)
			throws PrinterException {
		int y = 0;
		int x = 0;
//		System.out.println("??????????????");
		Graphics2D g2 = (Graphics2D) gp;
		// Graphics2D g3 = (Graphics2D) gp;
		g2.setPaint(Color.black); // 设置打印颜色为黑色
		if (page >= PAGES) // 当打印页号大于需要打印的总页数时，打印工作结束
			return Printable.NO_SUCH_PAGE;
		g2.translate(pf.getImageableX(), pf.getImageableY());// 转换坐标，确定打印边界
//		System.out.println("!!!!!!!!!!!!");
		ToPrint(g2, x, y);
		return 0; // 存在打印页时，继续打印工作
	}

	// 打印内容到指定位置
	public void printContent() {
		String printName = ConfigurableConstants.getProperty("defaultPrint");
//		String printName ="Canon MP250";
		System.out.println("打印机名称"+printName);
		PAGES = 1; // 获取打印总页数
		// 指定打印输出格式
		DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
		DocAttributeSet das = new HashDocAttributeSet();
		// 定位默认的打印服务
		// PrintService printService =
		// PrintServiceLookup.lookupDefaultPrintService();
		/*
		 * if("1".equals(goodplan.getGoodPlan_Type())){ printName="2lou"; }
		 * if("2".equals(goodplan.getGoodPlan_Type())){ printName="4lou"; }
		 */

		// printName=goodplan.getPrint_name();
		PrintService[] printServices = PrintServiceLookup.lookupPrintServices(
				flavor, das);
		for (int i = 0; i < printServices.length; i++) {
			// System.out.println(printServices[i].getName()+"已打印"+"  printName:"+printName);
			if (printName.equals(printServices[i].getName())) {
				// 创建打印作业
				DocPrintJob job = printServices[i].createPrintJob();
				// 设置打印属性
				PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
				// 设置纸张大小,也可以新建MediaSize类来自定义大小
				pras.add(MediaSizeName.ISO_A4);

				// 指定打印内容
				Doc doc = new SimpleDoc(this, flavor, das);
				// 不显示打印对话框，直接进行打印工作
				try {
					job.print(doc, pras); // 进行每一页的具体打印操作
				} catch (PrintException pe) {
					pe.printStackTrace();
				}

			}
		}

	}

	// 这里才是真正打印的地方.
	public void ToPrint(Graphics2D g2, int x, int y) {
		GoodPlan goodPlan = this.goodPlan;
//		System.out.println(goodPlan.getGoodPlan_Id() + "\t"
//				+ goodPlan.getProductList());
		y=+_y;
		g2.setFont(new Font("宋体", Font.PLAIN, _titleFontSize));
		 g2.drawString(doorStore.getDoorStore_Name()+"   "+goodType.trim()+"   "+goodPlan.getGoodPlan_date(),_x+90,y);
		 y=y+10;
	    g2.drawString("-----------------------------------------------------------------------------------------------------",_x-25,y);
		y = _y + step+step;
		 
		String deptName = "";
		if (goodPlan.getProductList() != null) {
			for (int i = 0; i < goodPlan.getProductList().size(); i++) {
				if (deptName == "" || !deptName.equals(goodPlan.getProductList().get(i).getProduct_Dept_Name())) {
					deptName =goodPlan.getProductList().get(i).getProduct_Dept_Name();
					if(i!=0)y = y + step + 30;
					g2.setFont(new Font("宋体", Font.PLAIN, _titleFontSize));
					g2.drawString(deptName,_x , y); // 具体打印每一行文本，同时走纸移位
					y=y+15;
					g2.setFont(new Font("宋体", Font.PLAIN, _contentFontSize));
					g2.drawString(Commons.FillSpace("序号", 6)
							+ Commons.FillSpace("名称", 12)
							+ Commons.FillSpace("数量", 8)
							+ Commons.FillSpace("规格", 11)
							+ Commons.FillSpace("单位", 4), _x, y);
					if(i+1<goodPlan.getProductList().size()){
						g2.drawString(Commons.FillSpace("序号", 6)
								+ Commons.FillSpace("名称", 12)
								+ Commons.FillSpace("数量", 8)
								+ Commons.FillSpace("规格", 11)
								+ Commons.FillSpace("单位", 4), _x2, y);
					}
					y=y+10;
					g2.drawString("-----------------------------------------------",_x - 25, y);
					if(i+1<goodPlan.getProductList().size()){
						g2.drawString("-----------------------------------------------",_x2 - 25, y);
					}
				}
				String name = goodPlan.getProductList().get(i)
						.getProduct_Name().trim();
				String quantity = goodPlan.getProductList().get(i)
						.getProduct_Quantity().trim();
				String unit = goodPlan.getProductList().get(i)
						.getProduct_Unit().trim();
				String guige = goodPlan.getProductList().get(i)
						.getProduct_Specification().trim();
		    		   y=y+step;
		    		   g2.drawString(Commons.FillSpace(Integer.toString(i+1),6)+Commons.FillSpace(name,12)+Commons.FillSpace(quantity,8)+Commons.FillSpace(guige,11)+Commons.FillSpace(unit,4), _x, y);
                    if(i+1<goodPlan.getProductList().size()){
                    	i++;
                    	if (deptName != "" && deptName.equals(goodPlan.getProductList().get(i).getProduct_Dept_Name())) {
                       	 name = goodPlan.getProductList().get(i)
   						.getProduct_Name().trim();
   				 quantity = goodPlan.getProductList().get(i)
   						.getProduct_Quantity().trim();
   				 unit = goodPlan.getProductList().get(i)
   						.getProduct_Unit().trim();
   				 guige = goodPlan.getProductList().get(i)
   						.getProduct_Specification().trim();
   		    		   g2.drawString(Commons.FillSpace(Integer.toString(i+1),6)+Commons.FillSpace(name,12)+Commons.FillSpace(quantity,8)+Commons.FillSpace(guige,11)+Commons.FillSpace(unit,4), _x2, y);
                    	}else{
                    		i--;
                    	}
                    	
					}
			}
		}
	}

	public void PrintReport2(DoorStore doorStore, String type, Graphics2D g2,
			int x, int y) {

	}

	/**
	 * @param obj
	 */

	public void PrintReady(String type) {
		// 按门店循环.一个门店一个门店的打印.
		DoorStoreService doorStoreService = new DoorStoreService();
		List<DoorStore> doorStoreList = doorStoreService.queryAll();
		for (int i = 1; i < doorStoreList.size(); i++) {
			this.doorStore = doorStoreList.get(i);
			this.type = type;
			GoodPlan goodPlan = new GoodPlan();
			goodPlan.setGoodPlan_Type(type);
			goodPlan.setDoorStore_Id(doorStore.getDoorStore_Id());
			goodPlan.setDoorStore_Name(doorStore.getDoorStore_Name());
			if ("2".equals(type)) {
				String date = new SimpleDateFormat("yyyy-MM-dd")
						.format(Calendar.getInstance().getTime());
				goodPlan.setGoodPlan_BeginDate(date + " 04:00:00");
				goodPlan.setGoodPlan_EndDate(date + " 23:00:00");
//				goodPlan.setGoodPlan_BeginDate("2012-06-19" + " 00:00:00");
//				goodPlan.setGoodPlan_EndDate("2012-06-19" + " 23:59:59");
				goodPlan.setGoodPlan_Type("2");
				this.goodType = "下午补货单";
			} else if ("3".equals(type)) {
				String date = new SimpleDateFormat("yyyy-MM-dd")
						.format(Calendar.getInstance().getTime());
				String yesterday = new SimpleDateFormat("yyyy-MM-dd")
						.format(new Date(System.currentTimeMillis() - 1000 * 60
								* 60 * 24));// 获取昨天日期
//				goodPlan.setGoodPlan_BeginDate(yesterday + " 15:00:00");
//				goodPlan.setGoodPlan_EndDate(date + " 22:59:59");
				goodPlan.setGoodPlan_BeginDate(yesterday + " 00:00:00");
				goodPlan.setGoodPlan_EndDate(yesterday + " 23:59:59");
//				System.out.println(goodPlan.getGoodPlan_BeginDate()+"\t"+goodPlan.getGoodPlan_EndDate());
				goodPlan.setGoodPlan_Type("3");
				this.goodType = "次日补货单";
			}
			GoodPlanService goodPlanService = new GoodPlanService();
			this.goodPlan = goodPlanService
					.queryGoodPlanByDoorStoreAndType(goodPlan);
			if (this.goodPlan.getGoodPlan_Id() != null) {
				System.out.println("开始打印>>" + doorStore.getDoorStore_Name()+"\t");
				this.goodPlan=goodPlanService.queryPlanBodyByGoodPlanId(goodPlan);
//				for(int m=0;m<this.goodPlan.getProductList().size();m++){
//					System.out.println(this.goodPlan.getProductList().get(m).getProduct_Name()+"\t"+this.goodPlan.getProductList().get(m).getProduct_Dept_Name());
//				}
				printContent();
			}

		}
	}

	public static void main(String args[]) throws FileNotFoundException,
			MalformedURLException {
		PrintGoodPlanReport2 p = new PrintGoodPlanReport2();
		p.PrintReady("2");
	}
}
